import cv2
import time
from gesture import handDetector
from selenium import webdriver
from selenium.webdriver.common.keys import Keys


class gestureControl():
    def __init__(self):
        self.cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
        self.cap.set(5, 1)
        self.detector = handDetector()
        self.lastkey = ''
        self.lasturl = ''
        self.lasthandles = []
        self.loopcount = 0
        self.driver = webdriver.Edge()        
    
    def gestureDistinguish(self):
        ret, img = self.cap.read()
        # cv2.imshow('test', img)
        # cv2.waitKey(0)
        img = self.detector.findHands(img)
        lmList = self.detector.findPosition(img, draw=False)
        if not lmList:
            self.lastkey = ''
            return
        fingerList, heading = self.detector.fingerStatus(lmList)
        gesture = ''
        if fingerList == [True] * 5:
            gesture = 'Five'
        elif fingerList == [False] * 5:
            gesture = 'Fist'
        elif fingerList == [False, True, False, False, False]:
            gesture = 'Index_' + heading
        elif fingerList == [False, True, True, False, False] or fingerList == [True, True, True, False, False]:
            gesture = 'Double_' + heading
        elif fingerList == [True, False, False, False, False]:
            gesture = 'Thumb_' + heading
        elif fingerList == [False, False, True, True, True]:
            gesture = 'Three'
        elif fingerList == [True, True, False, False, False]:
            gesture = 'Eight_' + heading
        if gesture == self.lastkey and gesture not in ('Eight_left', 'Eight_right'):
            return
        self.lastkey = gesture
        return gesture
        

    def handleGestureControl(self, gesture):
        print(gesture)
        clickCode = "if (document.getElementsByClassName('{0}')[0]) {{document.getElementsByClassName('{0}')[0].click();}}"
        if 'bilibili.com/video' in self.driver.current_url:
            if gesture == 'Index_up' or gesture == 'Eight_up':
                self.driver.execute_script('player.prev()')
            elif gesture == 'Index_down' or gesture == 'Eight_down':
                self.driver.execute_script('player.next()')
            elif gesture == 'Five':
                self.driver.execute_script(clickCode.format('bpx-player-ctrl-play'))
            elif gesture == 'Thumb_up':
                self.driver.execute_script(clickCode.format('like'))
            elif gesture == 'Three':
                ele = self.driver.find_element_by_class_name('like')
                self.tripleAction = webdriver.ActionChains(self.driver)
                self.tripleAction.click_and_hold(ele)
                self.tripleAction.pause(3.5)
                self.tripleAction.release(ele)
                self.tripleAction.perform()
            elif gesture == 'Eight_left' or gesture == 'Index_left':
                self.skipAction = webdriver.ActionChains(self.driver)
                self.skipAction.send_keys(Keys.LEFT)
                self.skipAction.perform()
            elif gesture == 'Eight_right' or gesture == 'Index_left':
                self.skipAction = webdriver.ActionChains(self.driver)
                self.skipAction.send_keys(Keys.RIGHT)
                self.skipAction.perform()
            elif gesture == 'Double_up':
                self.driver.execute_script('var pbr=[0.5, 0.75, 1.0, 1.25, 1.5, 2.0];\
                                            var index=pbr.indexOf(player.getPlaybackRate());\
                                            if (index<pbr.length-1) {player.setPlaybackRate(pbr[index+1]);}\
                                            else {player.setPlaybackRate(pbr[0]);}')
            elif gesture == 'Double_down':
                self.driver.execute_script('player.setMuted(!player.getMuted())')
            elif gesture == 'Fist':
                self.driver.execute_script(clickCode.format('bpx-player-ctrl-web'))

            self.lasturl = self.driver.current_url

    def loop(self):
        time.sleep(3)
        while True:
            gesture = self.gestureDistinguish()
            if self.lasthandles != self.driver.window_handles and self.driver.window_handles:
                self.driver.switch_to.window(self.driver.window_handles[-1])
            if gesture:
                self.handleGestureControl(gesture)
                time.sleep(1)
            self.lasthandles = self.driver.window_handles
            self.loopcount += 1
            time.sleep(0.5)


if __name__ == '__main__':
    engine = gestureControl()
    engine.loop()